import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:hktk_app/dao/subject_dao.dart';
import 'package:hktk_app/decoration/chapter_expansion_tile.dart';
import 'package:hktk_app/exception/dao_exception.dart';
import 'package:hktk_app/model/data_model.dart';
import 'package:hktk_app/model/subject/chapter_model.dart';
import 'package:hktk_app/util/data_util.dart';
import 'package:hktk_app/util/event_bus_util.dart';
import 'package:hktk_app/util/font_util.dart';
import 'package:hktk_app/util/toast_util.dart';
import 'package:hktk_app/util/view_util.dart';
import 'package:hktk_app/widget/subject/chapter_indent_widget.dart';
import 'package:hktk_app/widget/subject/chapter_leaf_widget.dart';
import 'package:hktk_app/widget/subject/chapter_show_qnum_widget.dart';

/// 章节可展开组件
class ChapterExpandableWidget extends StatefulWidget {
  /// 对应章节数据
  final ChapterModel chapterModel;

  /// 栏目id
  final String columnId;

  /// 是否免费，true：免费，false：不免费
  final bool free;

  /// 科目id
  final int categoryId;

  /// 是否在第一位时打开对应数据
  final bool opening;

  /// 是否是第一次打开
  final bool init;

  const ChapterExpandableWidget({
    super.key,
    required this.chapterModel,
    required this.columnId,
    required this.free,
    required this.opening,
    required this.init,
    required this.categoryId,
  });

  @override
  State<ChapterExpandableWidget> createState() =>
      _ChapterExpandableWidgetState();
}

class _ChapterExpandableWidgetState extends State<ChapterExpandableWidget> {
  late BuildContext _context;

  /// 控制器
  late ChapterExpansionTileController _controller;

  /// 是否处于打开模式
  late bool _isOpenIt;

  /// 子组件数据，懒加载·
  late List<ChapterModel> _childList;

  /// 数据是否加载完成
  late bool _dataInit;

  /// 监听方法章节刷新方法
  late StreamSubscription<EventChapterRefresh> _eventChapter;

  @override
  void initState() {
    super.initState();
    debugPrint(
        "chapterExpandableWidget 组件 -> initState 方法执行 ===> ${widget.chapterModel.name}");
    debugPrint("");
    _controller = ChapterExpansionTileController();
    _isOpenIt = false;
    _childList = [];
    _dataInit = false;
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      if (widget.opening) {
        _controller.expand();
      }
    });

    // 监听方法
    _eventChapter = eventBus.on<EventChapterRefresh>().listen((event) {
      debugPrint(
          "chapterExpandableWidget 组件 -> 监听章节刷新方法执行 ===> ${widget.chapterModel.name} : $_isOpenIt");
      if (_isOpenIt) {
        _handleRefresh();
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    debugPrint(
        "chapterExpandableWidget 组件 -> dispose 方法执行 ===> ${widget.chapterModel.name}");
    debugPrint("");
    _eventChapter.cancel();
  }

  @override
  Widget build(BuildContext context) {
    debugPrint(
        "chapterExpandableWidget 组件 -> build 方法执行 ===> ${widget.chapterModel.name}");
    debugPrint("");
    _context = context;
    return ChapterExpansionTile(
      controller: _controller,
      // 监听是否打开
      onExpansionChanged: _onChangedFun,
      // 父组件显示样式
      title: _title(),
      // 是否显示分割线
      dividerDisplayTime: DividerDisplayTime.never,
      // 子集组件
      children: _subItems(),
    );
  }

  /// title 组件显示，展开集合标题
  _title() {
    return Column(
      children: [
        _titleTopItem(),
        _bottomItem(),
      ],
    );
  }

  /// 标题显示
  _titleTopItem() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Expanded(
          child: Row(
            children: [
              SvgPicture.asset(
                _isOpenIt
                    ? "images/home/course_zk.svg"
                    : "images/home/course_bh.svg",
                width: 32,
                height: 32,
              ),
              hiSpace(width: 16),
              Expanded(
                child: Text(
                  widget.chapterModel.name!,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: FontUtil.fontBlack1(28, fontWeight: FontWeight.w500),
                ),
              ),
            ],
          ),
        ),
        Icon(
          _isOpenIt ? Icons.expand_less : Icons.expand_more,
          size: 40,
        ),
      ],
    );
  }

  /// 底部显示组件
  _bottomItem() {
    return ChapterIndentWidget(
      indent: 17,
      paddingLeft: 17,
      height: 48,
      child: ChapterShowQnumWidget(
        qCount: widget.chapterModel.qcount!,
        num: widget.chapterModel.ztNum!,
        showQuestion: true,
      ),
    );
  }

  /// 子集组件
  _subItems() {
    List<Widget> list = [];
    if (_childList.isNotEmpty) {
      list.add(_indentItem(height: 48));
      for (int i = 0; i < _childList.length; i++) {
        ChapterModel model = _childList[i];
        if (model.leaf!) {
          // 最后一级
          list.add(_indentItem(
            child: ChapterLeafWidget(
              chapter: model,
              columnId: widget.columnId,
              free: widget.free,
            ),
          ));
          // 添加间距
          if (i != _childList.length - 1) {
            list.add(_indentItem(height: 30));
          }
        } else {
          // 不是最后一级
          list.add(_indentItem(
            child: ChapterExpandableWidget(
              chapterModel: model,
              columnId: widget.columnId,
              free: widget.free,
              opening: i == 0 && widget.opening && widget.init,
              init: widget.init,
              categoryId: widget.categoryId,
            ),
          ));
        }
      }
      list.add(_indentItem(height: 48));
    }
    return list;
  }

  /// 缩进组件显示
  _indentItem({
    double? height,
    Widget? child,
  }) {
    return ChapterIndentWidget(
      indent: 17,
      paddingLeft: 17,
      height: height,
      child: child,
    );
  }

  /// 监听是否打开方法
  void _onChangedFun(bool value) {
    debugPrint(
        "chapterExpandableWidget 组件 -> ${widget.chapterModel.name} 是否打开 ===> $value");
    if (value && !_dataInit) {
      // 开启加载框
      ToastUtil.loadingBoxShow(_context);
      // 加载数据
      _childrenInit().then((Map<String, dynamic> map) {
        // 结束加载框
        ToastUtil.loadingBoxRemove();
        if (map["suc"]) {
          _isOpenIt = value;
          setState(() {});
        } else {
          // 折叠，不打开
          _controller.collapse();
          ToastUtil.show(context: _context, msg: map["msg"]);
        }
      });
    } else {
      setState(() {
        _isOpenIt = value;
      });
    }
  }

  /// 加载相关数据方法
  Future<Map<String, dynamic>> _childrenInit() async {
    Map<String, dynamic> map = {};
    try {
      // 加载子集数据
      _childList = await SubjectDao.childChapter(
        columnId: widget.columnId,
        pId: widget.chapterModel.id!,
      );
      if (_childList.isEmpty) {
        return {"suc": false, "msg": "暂无数据"};
      }

      // 获取做题数量
      DataModel dataModel = dataUtilComm.dataModel;
      List<String> ids = _childList.map((v) => v.id!).toList();
      Map<String, dynamic> idsMap = await SubjectDao.chapterRecordsIds(
        industryCode: dataModel.industryId,
        examId: dataModel.examId,
        categoryId: widget.categoryId,
        chapterIds: ids,
      );
      for (ChapterModel model in _childList) {
        Map<String, dynamic> map2 = idsMap[model.id];
        if (map2["dc"] != null) {
          model.ztNum = map2["dc"];
        }
      }

      _dataInit = true;
      map["suc"] = true;
    } catch (e) {
      debugPrint(
          "chapterExpandableWidget 组件 -> ${widget.chapterModel.name} 章节请求发生异常 ===> $e");
      map = {"suc": false, "msg": "未知错误，请重试"};
      if (e is DaoException) {
        debugPrint(
            "chapterExpandableWidget 组件 -> ${widget.chapterModel.name} 章节dao异常 ===> ${e.msg}");
        map["msg"] = e.msg;
      }
    }
    return map;
  }

  /// 刷新方法
  void _handleRefresh() async {
    debugPrint(
        "chapterExpandableWidget 组件 -> 刷新方法开始 ===> ${widget.chapterModel.name}");
    dataUtilComm.chapterRefreshState
        .addRefreshState(id: widget.chapterModel.id!);
    await _childrenInit().then((Map<String, dynamic> map) {
      debugPrint(
          "chapterExpandableWidget 组件 -> 刷新异步加载方法结束 ===> ${widget.chapterModel.name}");
      dataUtilComm.chapterRefreshState
          .finishRefreshState(id: widget.chapterModel.id!);
      if (map["suc"]) {
        // setState(() {});
      } else {
        ToastUtil.show(context: _context, msg: map["msg"]);
      }
    });
    debugPrint(
        "chapterExpandableWidget 组件 -> 刷新方法结束 ===> ${widget.chapterModel.name}");
  }
}
